<script setup>
// 标签数据
import { reactive, ref } from "vue";
import { Delete, Edit, RefreshRight, Search, Plus } from "@element-plus/icons-vue";
import { addTag, findTagPageList, selectById, updateTag, deleteTag } from "@/api/admin/tag.js";
import { findAllCategory } from "@/api/common/common.js"
import { showMessage, showModel } from "@/composables/util.js";
import moment from 'moment'
// 定义响应式的表单对象
const form = reactive({
  name: '',
  startDate: '',
  endDate: '',
})

// 监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
  form.startDate = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
  form.endDate = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
  console.log('开始时间：' + form.startDate + ', 结束时间：' + form.endDate)
}

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const pickDate = ref('')
// 表单引用
const searchForm = ref(null)

// 重置查询条件
const reset = () => {
  form.name = ''
  form.startDate = ''
  form.endDate = ''
  pickDate.value = ''
}

// 标签分页数据
const tagList = ref([])
// 当前页码，初值默认为1
const current = ref(1)
// 总记录数，初值默认为0
const total = ref(0)
// 每页显示的记录数，初值默认为10
const size = ref(10)
//标签输入框值
const inputValue = ref('')
//输入的标签数组
const dynamicTags = ref([])
//控制标签输入框是否显示
const inputVisible = ref(false)
// 标签输入框引用
const InputRef = ref()

// 文章分类获取
const categories = ref([])
findAllCategory().then((res) => {
  console.log('获取分类数据：' + JSON.stringify(res.data.data))
  categories.value = res.data.data
})

// 获取分页数据
function getTagPageList() {
  // 调用后台分页接口，并传入所需参数
  findTagPageList({ current: current.value, size: size.value, name: form.name, startDate: form.startDate, endDate: form.endDate })
    .then((res) => {
      if (res.data.success == true) {
        console.log("标签数据" + JSON.stringify(res.data.data))
        tagList.value = res.data.data
        current.value = res.data.current
        size.value = res.data.size
        total.value = res.data.total
      }
    })
}
getTagPageList()
// 控制新增弹出框
const insertdialogVisible = ref(false)
// 新增标签时传递表单
const addTagForm = reactive({
  categoryId: null,
  tags: []
})

// 新增标签信息
const saveSubmit = () => {
  addTagForm.tags = dynamicTags
  //调用后端新增分类接口
  addTag(addTagForm).then((res) => {
    if (res.data.success === true) {
      // 提示修改成功
      showMessage('新增成功')
      insertdialogVisible.value = false
      addTagForm.categoryId = null
      // 存在Bug:新增一次标签后，再次点击新增无法弹出标签选项
      addTagForm.tags = null
      getTagPageList()
      //window.location.reload()
    } else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}

const tagId = ref()
// 控制修改弹出框
const updatedialogVisible = ref(false)
// 修改标签时传递表单
const updateTagForm = reactive({
  id: tagId,
  name: ''
})

// 修改标签信息
const updateSubmit = () => {
  // 调用后端修改标签接口
  updateTag(updateTagForm).then((res) => {
    if (res.data.success === true) {
      // 提示修改成功
      showMessage('修改成功')
      updatedialogVisible.value = false
      getTagPageList()
    } else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}

const selectOne = (id) => {
  updatedialogVisible.value = true
  selectById({ id: id }).then((res) => {
    if (res.data.success === true) {
      updateTagForm.id = res.data.data.id
      updateTagForm.name = res.data.data.name
    } else {
      let message = res.data.message
      console.log(message)
      // 提示消息
      showMessage(message, 'error')
    }
  })
}

//删除标签
const deleteSubmit = (id) => {
  console.log(id)
  showModel('是否删除该标签?').then(() => {
    deleteTag({ id }).then((res) => {
      if (res.data.success == true) {
        showMessage('删除成功')
        // 重新请求分页接口，渲染数据
        getTagPageList()
      } else {
        // 获取服务端返回的错误消息
        let message = res.data.message
        // 提示错误消息
        showMessage(message, 'error')
      }
    })
  }).catch(() => {
    console.log('取消了')
  })
}

// 存储选中项的ID数组
const selectedIds = ref([]);
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
  console.log(selectedIds)
};



const handleClose = (tag) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value.input.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

// 每页展示数量变更事件
const handleSizeChange = (chooseSize) => {
  size.value = chooseSize
  getTagPageList()
}

function handleIndex(index) {
  // 假设分页参数为 current（当前页）和 size（每页条数）
  return (current.value - 1) * size.value + index + 1;
}

</script>

<template>
  <!-- 查询表单 -->
  <el-form ref="searchForm" :model="form" style="
        margin:-10px 0 15px -10px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px 20px;
    " class="card" shadow="always" inline>
    <el-form-item prop="name" style="
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        ">
      <el-text style="min-width: 60px; margin-right: 15px; text-align: center">标签名称</el-text>
      <el-input v-model="form.name" style="width: 220px" prefix-icon="Search" placeholder="请输入" />
    </el-form-item>

    <el-form-item style="
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;">
      <el-text style="min-width: 60px; margin-right: 15px; text-align: center">创建日期</el-text>
      <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
        end-placeholder="结束时间" size="default" :shortcuts="shortcuts" style="width: 360px" @change="datepickerChange" />
    </el-form-item>

    <el-form-item style="margin-left: 10px; justify-content: center; padding-top: 14px">
      <el-button type="primary" plain :icon="Search" style="padding: 8px 20px;" @click="getTagPageList">
        查询
      </el-button>
      <el-button type="warning" plain :icon="RefreshRight" style="margin-left: 12px; padding: 8px 20px;" @click="reset">
        重置
      </el-button>
      <el-button type="success" plain :icon="Plus" style="padding: 8px 20px;"
        @click="insertdialogVisible = true">新增</el-button>
      <el-button type="danger" plain :icon="Delete" style="padding: 8px 20px;">批量删除</el-button>
    </el-form-item>
  </el-form>

  <!--数据展示区-->
  <div style="margin:-10px 0 15px -10px" class="card" shadow="always">
    <el-table :data="tagList" style="width: 100%" @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column type="index" :index="handleIndex" label="序号" width="80px" />
      <el-table-column property="name" label="标签名称">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" :content="scope.row.name" placement="top">
            <div class="text-overflow" style="width: 78px">{{ scope.row.name }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column property="count" label="该标签下课程数">
        <template #default="scope">
          {{ scope.row.articleTotal + scope.row.videoTotal }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button style="margin-left: 8px" type="primary" plain :icon="Edit" circle
            @click="selectOne(scope.row.id)"></el-button>
          <el-button style="margin-left: 8px" type="danger" plain :icon="Delete" circle
            @click="deleteSubmit(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="current" :page-size="[10, 20, 50]" :size="size" :disabled="disabled"
        background layout="total, prev, pager, next" :total="total" @size-change="handleSizeChange"
        @current-change="getTagPageList" />
    </div>


    <!--要单独拿出来，否则会被循环重复渲染-->
    <el-dialog v-model="insertdialogVisible" title="添加标签" width="600" append-to-body="true" align-center>
      <el-form :model="addTagForm">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="addTagForm.categoryId" clearable placeholder="---请选择---" size="large">
            <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tags">
          <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)" size="large">
            {{ tag }}
          </el-tag>
          <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" size="large"
            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else size="large" @click="showInput">
            新增标签
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="insertdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSubmit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--要单独拿出来，否则会被循环重复渲染-->
    <el-dialog v-model="updatedialogVisible" title="修改标签" width="600" append-to-body="true" align-center>
      <el-form :model="updateTagForm">
        <el-form-item label="标签名称" prop="name" label-width="80px" size="large">
          <el-input v-model="updateTagForm.name" autocomplete="off" placeholder="请输入标签" maxlength="20" show-word-limit
            clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updatedialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateSubmit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped></style>